const bcrypt = require('bcryptjs')
const { 
    useraFormateError,
    userAlreadyExited,
    userRegisterError,
    userDoesNotExist,
    userInvalidPassword
 } = require('../constant/err.type')
 const {
    isUserNameExist,
    getPasswordByUserName
 } = require('../service/user.service')

/**
 * 校验用户名或密码是否为空
 */
const userValidator = async (ctx, next) => {
    const { user_name, password } = ctx.request.body
    if(!user_name || !password) {
        ctx.app.emit('error', useraFormateError, ctx)
        return
    }
    await next()
}

/**
 * 校验用户
 * @param {*} ctx 
 * @param {*} next 
 * @returns 
 */
const verifyUser = async (ctx, next) => {
    const { user_name } = ctx.request.body
    try {
        const res  = await isUserNameExist(user_name)
        if(Array.isArray(res) && res.length > 0){
            ctx.app.emit('error', userAlreadyExited, ctx)
            return
        }
    } catch (err) {
        ctx.app.emit('error', userRegisterError, ctx)
        return
    }
    
    await next()
}

/**
 * 密码加密
 */
const cryptPassword = async(ctx, next) => {
    const { password } = ctx.request.body
    const salt = bcrypt.genSaltSync(10)
    const hash = bcrypt.hashSync(password, salt)
    ctx.request.body.password = hash

    await next()
}

/**
 * 登录验证
 * @param {*} ctx 
 * @param {*} next 
 */
const verifyLogin = async(ctx, next) => {
    const { user_name, password } = ctx.request.body
    const res = await isUserNameExist(user_name)
    if(Array.isArray(res) && res.length > 0){
        // 校验传入密码和数据库中的密码是否相等
        const passwordFromSql = await getPasswordByUserName(user_name)        
        if (!bcrypt.compareSync(password, passwordFromSql)) {
            ctx.app.emit('error', userInvalidPassword, ctx)
            return
        }
    } else {
        ctx.app.emit('error', userDoesNotExist, ctx)
        return
    }

    await next()
}


module.exports = {
    userValidator,
    verifyUser,
    cryptPassword,
    verifyLogin
}